package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"strconv"
	"time"
)

const (
	PRINT_ERROR int64 = 0
	PRINT_WARN  int64 = 1
	PRINT_INFO  int64 = 2
	PRINT_DEBUG int64 = 3
)

var MyPrintLogGrade int64

func init() {
	MyPrintLogGradeStr, err := Config.Get("myPrintLogGrade")
	if err != nil {
		MyPrint(PRINT_ERROR, err.Error())
		os.Exit(1)
	}
	MyPrintLogGrade, err = strconv.ParseInt(MyPrintLogGradeStr, 10, 64)
	if err != nil {
		MyPrint(PRINT_ERROR, err.Error())
		os.Exit(1)
	}
}

func MyPrint(printGrade int64, a ...interface{}) {
	if printGrade > MyPrintLogGrade {
		return
	}
	_, file, line, ok := runtime.Caller(1)
	if !ok {
		file = "???"
		line = 0
	} else {
		file = filepath.Base(file)
	}
	b := make([]interface{}, len(a)+1)
	b[0] = time.Now().Format("20060102150405") + fmt.Sprintf("%s:%d", file, line)
	for i := 0; i < len(a); i++ {
		if reflect.ValueOf(a[i]).Kind() == reflect.Ptr {
			b[i+1] = toString(a[i])
		} else {
			b[i+1] = a[i]
		}
	}
	fmt.Println(b...)
}
func toString(this interface{}) string {
	b, err := json.Marshal(this)
	if err != nil {
		return fmt.Sprintf("%+v", this)
	}
	var out bytes.Buffer
	err = json.Indent(&out, b, "", "    ")
	if err != nil {
		return fmt.Sprintf("%+v", this)
	}
	return out.String()
}

func MyPrintCaller(printGrade int64, deepSkip int, a ...interface{}) {
	if printGrade > MyPrintLogGrade {
		return
	}
	_, file, line, ok := runtime.Caller(deepSkip)
	if !ok {
		file = "???"
		line = 0
	} else {
		file = filepath.Base(file)
	}
	b := make([]interface{}, len(a)+1)
	b[0] = time.Now().Format("20060102150405") + fmt.Sprintf("%s:%d", file, line)
	for i := 0; i < len(a); i++ {
		if reflect.ValueOf(a[i]).Kind() == reflect.Ptr {
			b[i+1] = toString(a[i])
		} else {
			b[i+1] = a[i]
		}
	}
	fmt.Println(b...)
}
